package cc.vicp.djx314.starfood.web.user;

import java.io.IOException;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cc.vicp.djx314.starfood.domain.account.User;
import cc.vicp.djx314.starfood.service.account.UserInfoService;
import cc.vicp.djx314.starfood.service.exception.UserNotFoundException;
import cc.vicp.djx314.starfood.web.exception.UserNotSameAsSessionException;
import cc.vicp.djx314.starfood.web.exception.UserSessionTimeOutException;

@Controller
public class UserInfoController {
	public static final Logger logger = LoggerFactory.getLogger(UserInfoController.class);

	@Autowired
	private UserInfoService userInfoService;

	@RequestMapping(value = "/user/image/{id}.jpg", method = RequestMethod.GET)
	@ResponseBody
	public byte[] getUserHeadImg(@PathVariable("id") Integer id)
			throws UserNotFoundException, IOException {
		try {
			Resource userImg = userInfoService.getUserHeadImg(id);
			return FileCopyUtils.copyToByteArray(userImg.getInputStream());
		} catch (IOException e2) {
			logger.error("io流发生未知错误", e2);
			throw e2;
		}
	}

	@RequestMapping(value = "/user/info/{id}", method = RequestMethod.GET)
	public String getUserInfo(@PathVariable("id") Integer id, Model model,
			HttpSession session)
					throws UserSessionTimeOutException, UserNotSameAsSessionException, UserNotFoundException {
		User user = (User) session.getAttribute("loginUser");
		if (user == null) {
			throw new UserSessionTimeOutException("用户session过时");
		}
		if (id.equals(user.getId()) == false) {
			throw new UserNotSameAsSessionException("请求的用户id:  " + id +
					"  与session的用户id:  " + user.getId() + "  不符");
		}
		User userInfo = userInfoService.getAllUserInfo(id);
		model.addAttribute("user", userInfo);
		return "customer/user/userinfo";
	}
}